<template>
  <div>
    <el-upload
      :action="uploadUrl"
      :headers="headers"
      :on-success="handleSuccess"
      :on-error="handleError"
      :on-progress="handleProgress"
      :before-upload="beforeUpload"
      :on-change="handleChange"
      :file-list="getFileList"
      :disabled="disabled"
      :accept="accept"
      :data="uploadData"
      :limit="limit"
      :http-request="uploadAction"
      :auto-upload="false"
      :on-exceed="handleExceed"
      multiple
    >
      <div class="box">
        <p class="mr">
          <el-icon><Plus /></el-icon>
        </p>
        <div class="el-upload__tip" v-if="isAccept">
          请上传{{ accept }}格式的文件，不超过{{ limit }}个
        </div>
      </div>
    </el-upload>
    <el-progress
      :stroke-width="3"
      v-if="isProgress"
      :percentage="uploadProgress"
      :status="uploadStatus"
    ></el-progress>
  </div>
</template>

<script setup lang="ts">
import {
  ref,
  reactive,
  watch,
  defineProps,
  defineEmits,
  defineExpose,
  
} from "vue";
import { ElMessage } from "element-plus";
import axios from "axios";
import { md5Encrypt } from "@/utils/md5";
import { useUserSrote } from "@/stores/modules/user";
import { setBindAtt } from "@/api/public";

const userSrote = useUserSrote();

// 定义组件的props
const props = defineProps({
  // 是否禁用上传
  disabled: {
    type: Boolean,
    default: true,
  },
  // 是否显示
  isAccept: {
    type: Boolean,
    default: true,
  },
  // 接受的文件类型
  accept: {
    type: String,
  },
  // 数量限制
  limit: {
    type: Number,
    default: 3,
  },
  bailId: {
    type: Number,
  },
  groupId: {
    type: Number,
  },
  getFileList:{
    type: Array,
  }
});

let isProgress = ref(false);
let uploadProgress = ref(0);
let uploadStatus = ref("exception");
let fileList = ref([]);
console.log(props.getFileList)

// 自定义参数
let uploadData = ref({
  bail_id: props.bailId,
  group_id: props.groupId,
});


// 上传API的URL
let API = import.meta.env.VITE_APP_BASE_API;
const uploadUrl = ref(API + "/client/attachment/uploads");

// 上传方法
const uploadAction = async (options: { file: any; onProgress: any; onSuccess: any; onError: any; }) => {
  const { file, onProgress, onSuccess, onError } = options;
  console.log(options);

  const formData = new FormData();
  formData.append("file", file);
  formData.append("bail_id", props.bailId);
  formData.append("group_id", props.groupId);

  // 设置请求头部
  const params = Object.keys(uploadData.value)
    .sort()
    .map((key) => `${key}=${uploadData.value[key]}`)
    .join("&");
  const signature = md5Encrypt(
    params + `1IJWqH8Rh9/NTPCc6AGJujcPPFs4w4+Nbualhz7DbAgQ5k0Hd8ZJZg13yF+/mnz`
  );
  const headers = {
    token: userSrote.token,
    signature: signature,
    Accept: "multipart/form-data",
    "Content-Type": "multipart/form-data",
  };

  try {
    // 上传进度
    const response = await axios.post(uploadUrl.value, formData, {
      headers,
      onUploadProgress: (progressEvent) => {
        const percentCompleted = Math.round(
          (progressEvent.loaded * 100) / progressEvent.total
        );
        onProgress({ percent: percentCompleted });
      },
    });

    // 上传成功
    onSuccess(response.data);
    console.log(response.data);
    emit("success", response.data.data.success);
    // let data = {
    //   bail_id: props.bailId,
    //   group_id: props.groupId,
    //   attachment: response.data.data.success.join(","),
    // };
    // await getBindAtt(data).then((res) => {
    //   if (res.code == 1) {
    //     ElMessage.success("上传成功！");
        
    //   } else {
    //     ElMessage.error(res.msg);
    //   }
    // });
  } catch (error) {
    // 上传失败
    onError(error);
    ElMessage.error("上传失败！");
  }
};

const submitUpload = async () => {
  console.log(fileList.value);
  let formData = new FormData();
  fileList.value.forEach((file, index) => {
    formData.append(`file[${index}]`, file.raw);
  });
  formData.append("bail_id", props.bailId);
  formData.append("group_id", props.groupId);

  // 设置请求头部
  const params = Object.keys(uploadData.value)
    .sort()
    .map((key) => `${key}=${uploadData.value[key]}`)
    .join("&");
  const signature = md5Encrypt(
    params + `1IJWqH8Rh9/NTPCc6AGJujcPPFs4w4+Nbualhz7DbAgQ5k0Hd8ZJZg13yF+/mnz`
  );
  const headers = {
    token: userSrote.token,
    signature: signature,
    Accept: "multipart/form-data",
    "Content-Type": "multipart/form-data",
  };

  // 上传进度
  await axios
    .post(uploadUrl.value, formData, {
      headers,
    })
    .then((response) => {
      if (response.data.code == 1) {
        isProgress.value = true;
        const interval = setInterval(() => {
          if (uploadProgress.value >= 99) {
            uploadStatus.value = "success";
            ElMessage.success("文件上传成功");
            clearInterval(interval);
            return;
          }
          uploadProgress.value += 1;
        }, 10);
        emit("success", response.data.data.success);
      } else {
        ElMessage.error("文件上传失败");
        uploadStatus.value = "exception";
      }
    });
  
    
};
const onUploadProgress = (progressEvent: { loaded: number; total: number; }) => {
  const percentCompleted = Math.round(
    (progressEvent.loaded * 100) / progressEvent.total
  );
  uploadProgress.value = percentCompleted;
  if (percentCompleted === 100) {
    uploadStatus.value = "success";
  }
};
// 定义组件的emits
const emit = defineEmits(["update:file-list", "success"]);

// 监听文件列表变化
// watch(fileList, (newList) => {
//   emit("update:file-list", newList);
// });

const handleProgress = (e: any) => {
  console.log(e);
};

// 上传前处理函数
const beforeUpload = (file: { name: string; size: number; }) => {
  console.log(file);
  if (!file) return false;
  // 文件类型校验
  if (file.name) {
    console.log("aaa");
    const fileName = file.name.split(".");
    const fileExt = fileName[fileName.length - 1];
    const isTypeOk = props.accept.indexOf(fileExt) >= 0;
    console.log(isTypeOk);

    if (!isTypeOk) {
      ElMessage.error("格式不对");
      return false;
    }
  }

  // 文件大小校验
  if (file.size > 1024 * 1024 * 1) {
    // 限制文件大小为10MB
    ElMessage.error("文件不能超过10MB");
    return false;
  }
  return true;
};

// 文件变化处理函数
const handleChange = (file: any, newFileList: never[]) => {
  fileList.value = newFileList;
  console.log(fileList);
};

// 文件超出限制处理函数
const handleExceed = (files: any, fileList: any) => {
  ElMessage.warning(`最多只能上传 ${props.limit} 个文件`);
};

defineExpose({
  submitUpload,
});
// 组件生命周期钩子...
</script>

<style scoped lang="scss">
/* 自定义样式 */
.el-upload__tip {
  color: #f00;
  font-size: 12px;
  line-height: 40px;
  margin-left:10px;
}

.mr {
  width: 80px;
  height: 80px;
  border-radius: 8px;
  background: #fff;
  font-size:30px;
  color:#999;
  // background: #f5f7fa;
  display: flex;
  align-items: center;
  justify-content: center;
  border:1px solid #f5f5f5;
  img {
    width: 51px;
    height: 51px;
  }
}
.box {
  display: flex;
  min-width: 150px;
}
</style>